  <template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="产品编号">
              <el-input v-model="searchForm.deviceCode" placeholder="产品编号" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品类型">
              <el-select v-model="searchForm.deviceTypeId" filterable placeholder="请选择产品类型">
                <el-option v-for="item in deviceTypeDic" :key="item.deviceTypeId"
                  :label="item.deviceTypeName + ' ' + item.deviceClassify + ' ' + item.deviceTypeCode"
                  :value="item.deviceTypeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="产品状态">
              <el-select v-model="searchForm.deviceStatus" filterable placeholder="请选择产品状态">
                <el-option v-for="item in deviceStatusDic" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="售出状态">
              <el-select v-model="searchForm.deviceSoldStatus" filterable placeholder="请选择售出状态">
                <el-option v-for="item in deviceSoldStatusDic" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <div>
        </div>

        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="产品编号" align="center">
          <template #default="{ row }">
            {{ row.deviceCode }}
          </template>
        </el-table-column>

        <el-table-column label="产品名称" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeDto==null?"暂无": row.deviceTypeDto.deviceTypeName }}
          </template>
        </el-table-column>

        <el-table-column label="产品型号" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeDto==null?"暂无": row.deviceTypeDto.deviceTypeCode }}
          </template>
        </el-table-column>

        <el-table-column label="产品状态" align="center">
          <template #default="{ row }">
            {{ formatDeviceStatus(row.deviceStatus) }}
          </template>
        </el-table-column>

        <el-table-column label="售出状态" align="center">
          <template #default="{ row }">
            {{ formatDeviceSoldStatus(row.deviceSoldStatus) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>
              <el-button type="primary" size="small" text @click="handleCreate(scope.row)">入库</el-button>
              <!-- 产品售出状态，1在库，2售出，3维修中 只有在库状态的才可出库 -->
              <el-button v-if="scope.row.deviceSoldStatus == 1" type="primary" size="small" text
                @click="handleDeviceOut(scope.row)">出库</el-button>
              <el-button v-else type="primary" size="small" text disabled>出库</el-button>
              <el-button type="primary" size="small" text @click="handleShowRecords(scope.row)">记录</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
          :page-size="limit" @current-change="initTableData" />
      </div>

      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">

        <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">

          <el-form-item label="产品编号" prop="deviceCode">
            <el-input v-model="form.deviceCode" placeholder="产品编号" disabled></el-input>
          </el-form-item>

          <el-form-item label="产品类型" prop="deviceTypeId">
            <el-select v-model="form.deviceTypeId" filterable placeholder="请选择产品类型" disabled>
              <el-option v-for="item in deviceTypeDic" :key="item.deviceTypeId" :label="item.deviceTypeName"
                :value="item.deviceTypeId">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 0维修, 1销售，2新生产，3其他 -->
          <el-form-item v-if="editId == 0" label="操作类型" prop="opType">
            <el-select @change="opTypeChange" v-model="form.opType" filterable placeholder="请选择操作类型">
              <el-option v-for="item in opTypeDic" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item v-if="editId == 0" label="设备状态" prop="deviceStatus">
            <el-select v-model="form.deviceStatus" filterable placeholder="请选择设备状态">
              <el-option v-for="item in deviceStatusDic" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item v-if="editId == 0 && form.opType != 2" label="申请人" prop="userId">
            <el-button @click="dialogTableVisible_user = true">
              {{ checkedUser == null ? '选择申请人' : checkedUser.realName }}
            </el-button>
          </el-form-item>

          <el-form-item v-if="editId == 0 && form.opType == 1" label="选择工单" prop="orderId">
            <el-button @click="dialogTableVisible_order = true">
              {{ checkedOrder == null ? '选择工单' : checkedOrder.orderName }}
            </el-button>
          </el-form-item>

          <el-form-item v-if="editId != 0" label="系统版本" prop="systemVersion">
            <el-input v-model="form.systemVersion" placeholder="系统版本"></el-input>
          </el-form-item>

          <el-form-item v-if="editId != 0" label="地址" prop="address">
            <el-input v-model="form.address" placeholder="地址"></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" :rows="4" v-model="form.remarks" placeholder="备注"></el-input>
          </el-form-item>

        </el-form>
      </FormDrawer>

      <!-- 出库弹窗 -->
      <FormDrawer ref="formDeviceOutDrawerRef" title="出库" @submit="handleDeviceOutSubmit">
        <el-form :model="formDeviceOut" ref="formDeviceOutRef" :rules="deviceOutRules" label-width="80px"
          :inline="false">
          <el-form-item label="产品编号" prop="deviceCode">
            <el-input v-model="formDeviceOut.deviceCode" placeholder="产品编号" disabled></el-input>
          </el-form-item>

          <el-form-item label="产品类型" prop="deviceTypeId">
            <el-select disabled v-model="formDeviceOut.deviceTypeId" @change="deviceTypeChange" filterable placeholder="请选择产品类型">
              <el-option v-for="item in deviceTypeDic" :key="item.deviceTypeId" :label="item.deviceTypeName"
                :value="item.deviceTypeId">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 0维修, 1销售，2新生产，3其他 -->
          <el-form-item label="操作类型" prop="opType">
            <el-select v-model="formDeviceOut.opType" filterable placeholder="请选择操作类型">
              <el-option v-for="item in opOutTypeDic" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="设备状态" prop="deviceStatus">
            <el-select v-model="formDeviceOut.deviceStatus" filterable placeholder="请选择设备状态">
              <el-option v-for="item in deviceStatusDic" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="申请人" prop="userId">
            <el-button @click="dialogTableVisible_user = true">
              {{ checkedUser == null ? '选择申请人' : checkedUser.realName }}
            </el-button>
          </el-form-item>

          <el-form-item label="选择工单" prop="orderId">
            <el-button @click="dialogTableVisible_order = true">
              {{ checkedOrder == null ? '选择工单' : checkedOrder.orderName }}
            </el-button>
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="formDeviceOut.remarks" placeholder="备注"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>

    <!-- 选择工单弹窗 -->
    <el-dialog v-model="dialogTableVisible_order" title="选择工单" width="70%" align-center>
      <SelectOrder v-if="dialogTableVisible_order" :showSelection="true"
        :selectedOrderId="form.orderId ? form.orderId : formDeviceOut.orderId" @getCheckedOrder="getCheckedOrder" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible_order = false">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择申请人弹窗 -->
    <el-dialog v-model="dialogTableVisible_user" title="选择申请人" width="70%" align-center>
      <SelectUser @getCheckedUser="getCheckedUser" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible_user = false">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择公司弹窗 -->
    <el-dialog v-model="dialogTableVisible_company" title="选择客户" width="70%" align-center>
      <SelectCompany @getCheckedCompany="getCheckedCompany" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible_company = false">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看出入库记录弹窗 -->
    <el-dialog v-model="dialogTableVisible_record" title="出入库记录" width="70%" align-center>
      <!-- 是否零件, 0设备, 1零件 -->
      <ShowRecord v-if="dialogTableVisible_record" :deviceId="showRecord_deviceId" :isPart="0" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible_record = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import { toast } from "~/composables/util"
import SelectCompany from "~/components/select-company.vue";
import SelectOrder from "~/components/select-order.vue";
import SelectUser from "~/components/select-user.vue";
import ShowRecord from "~/components/show-records.vue";
import { getDeviceList, deviceIn, deviceOut, updateDevice, getDeviceTypeList, formatDeviceStatus, formatDeviceSoldStatus } from "~/api/supply"
import { getUserInfo } from '~/utils/userInfo.js'

// 当前用户信息
const userInfo = ref({})

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableData = ref([])
const loading = ref(false)

//产品类型字典数据
const deviceTypeDic = ref([])

// 操作类型, 0维修, 1销售，2新生产，3其他
const opTypeDic = ref([{ "key": 2, "value": "新生产" }, { "key": 1, "value": "工单" }, { "key": 0, "value": "维修" }])

// 操作类型, 0维修, 1销售
const opOutTypeDic = ref([{ "key": 1, "value": "工单" }, { "key": 0, "value": "维修" }])

// 产品状态字典数据 0保内，1保外
const deviceStatusDic = ref([{ "key": 0, "value": "保内" }, { "key": 1, "value": "保外" }])

// 售出状态字典数据 1在库，2售出，3维修中
const deviceSoldStatusDic = ref([{ "key": 1, "value": "在库" }, { "key": 2, "value": "售出" }, { "key": 3, "value": "维修中" }])

//选择公司弹窗
const dialogTableVisible_company = ref(false)
const checkedCompany = ref(null)

//选择工单弹窗
const dialogTableVisible_order = ref(false)
const checkedOrder = ref(null)

//选择申请人
const dialogTableVisible_user = ref(false)
const checkedUser = ref(null)

// 查询条件
const searchForm = reactive({
  deviceCode: "",
  deviceStatus: null,
  deviceSoldStatus: null,
  deviceTypeId: null,
  page: currentPage.value,
  size: limit.value,
})

// 重置搜索框
const resetSearchForm = () => {
  searchForm.deviceCode = ""
  searchForm.deviceStatus = null
  searchForm.deviceSoldStatus = null
  searchForm.deviceTypeId = null
  initTableData(1)
}

// 生命周期函数
onMounted(() => {

  //获取当前用户信息
  userInfo.value = getUserInfo()

  //初始化产品类型
  initDeviceType()

  //初始化列表数据
  initTableData()
})

//初始化产品类型
function initDeviceType() {
  //查询全部
  let paramIo = {
    page: 1,
    size: 100,
  }
  getDeviceTypeList(paramIo)
    .then(res => {
      if (res) {
        deviceTypeDic.value = res.records
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getDeviceList(searchForm)
    .then(res => {
      if (res) {
        tableData.value = res.records
        total.value = res.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
  //操作类型；0维修, 1销售，2新生产，3其他
  opType: 2,
  //产品状态,0保内，1保外
  deviceStatus: 0,
  //产品售出状态，1在库，2售出，3维修中
  //deviceSoldStatus: 1,
  //工单ID
  orderId: null,
  //项目ID
  projectId: null,
  //客户ID
  customerId: null,
  //人员ID
  userId: null,
  //人员姓名
  userName: null,
  //产品编号
  deviceCode: null,
  //产品类型
  deviceTypeId: null,
  systemVersion: null,
  remarks: null,
  manufactureDate: null,
})

// 入库按钮点击事件
const handleCreate = (row) => {
  // console.log(JSON.stringify(row))
  //修改标记置为0
  editId.value = 0

  //将公司信息清空
  checkedCompany.value = null
  //将工单信息清空
  checkedOrder.value = null
  //将申请人信息清空
  checkedUser.value = null

  resetForm({
    //操作类型；0维修, 1销售，2新生产，3其他
    opType: 2,
    //产品状态,0保内，1保外
    deviceStatus: 0,
    //产品售出状态，1在库，2售出，3维修中
    //deviceSoldStatus: 1,
    //工单ID
    orderId: null,
    //项目ID
    projectId: null,
    //客户ID
    customerId: null,
    //人员ID
    userId: null,
    //人员姓名
    userName: null,
    //产品编号
    deviceCode: row.deviceCode,
    //产品类型
    deviceTypeId: row.deviceTypeDto.deviceTypeId,
    systemVersion: null,
    remarks: null,
    manufactureDate: null,
  })

  //打开弹窗
  formDrawerRef.value.open()
}

//执行表单校验
const rules = {
  opType: [
    { required: true, message: '操作类型不能为空', trigger: 'change' }
  ],
  // deviceStatus: [
  //   { required: true, message: '产品状态不能为空', trigger: 'change' }
  // ],
  num: [
    { required: true, message: '入库数量不能为空', trigger: 'change' }
  ],
  deviceCode: [
    { required: true, message: '产品编号不能为空', trigger: 'change' }
  ],
  orderId: [
    { required: true, message: '工单信息不能为空', trigger: 'change' }
  ],
  deviceTypeId: [
    { required: true, message: '产品类型不能为空', trigger: 'change' }
  ],
  userId: [
    { required: true, message: '申请人不能为空', trigger: 'change' }
  ]
}

//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "入库")
//提交表单
const handleSubmit = () => {
  //表单校验
  formRef.value.validate((valid) => {
    if (!valid) return

    console.log(JSON.stringify(form))

    //loading
    // formDrawerRef.value.showLoading()

    //入库-新产品入库
    if (editId.value == 0 && form.opType == 2) {
      form.userId = userInfo.value.id
      form.userName = userInfo.value.realName
    }
    //根据是否是修改标记，判断执行新增接口还是修改接口
    const fun = editId.value ? updateDevice(editId.value, form) : deviceIn(form)

    fun.then(res => {
      toast(drawerTitle.value + "成功")
      // 修改刷新当前页，新增刷新第一页
      initTableData(editId.value ? false : 1)
      formDrawerRef.value.close()
    }).finally(() => {
        //close loading
        formDrawerRef.value.hideLoading()
    })
  })
}

// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}


// 出库表单部分------------
const formDeviceOutDrawerRef = ref(null)
const formDeviceOutRef = ref(null)
const formDeviceOut = reactive({
  //操作类型；0维修, 1销售
  opType: 1,
  //产品状态,0保内，1保外
  // deviceStatus: 0,
  //工单ID
  orderId: null,
  //项目ID
  projectId: null,
  //客户ID
  customerId: null,
  //人员ID
  userId: null,
  //人员姓名
  userName: null,
  deviceCode: "",
  deviceTypeId: null,
  remarks: null
})
const deviceOutRules = {
  opType: [
    { required: true, message: '操作类型不能为空', trigger: 'change' }
  ],
  // deviceStatus: [
  //   { required: true, message: '产品状态不能为空', trigger: 'change' }
  // ],
  deviceCode: [
    { required: true, message: '产品编号不能为空', trigger: 'change' }
  ],
  orderId: [
    { required: true, message: '工单信息不能为空', trigger: 'change' }
  ],
  deviceTypeId: [
    { required: true, message: '产品类型不能为空', trigger: 'change' }
  ],
  userId: [
    { required: true, message: '申请人不能为空', trigger: 'change' }
  ]
}
//提交表单
const handleDeviceOutSubmit = () => {
  //表单校验
  formDeviceOutRef.value.validate((valid) => {
    if (!valid) return
    // console.log("出库入参：",JSON.stringify(formDeviceOut))
    //loading
    formDeviceOutDrawerRef.value.showLoading()

    //出库
    const fun = deviceOut(formDeviceOut)
    fun.then(res => {
      toast("出库成功")
      initTableData(false)
      formDeviceOutDrawerRef.value.close()
    })
      .finally(() => {
        formDeviceOutDrawerRef.value.hideLoading()
      })
  })
}
// 出库表单部分------------

// 出库
const handleDeviceOut = (row) => {
  //将工单信息清空
  checkedOrder.value = null
  //将申请人信息清空
  checkedUser.value = null
  //重置表单信息
  formDeviceOut.opType = 1
  formDeviceOut.orderId = null
  formDeviceOut.projectId = null
  formDeviceOut.customerId = null
  formDeviceOut.userId = null
  formDeviceOut.userName = null
  formDeviceOut.deviceCode = null
  formDeviceOut.deviceTypeId = null
  formDeviceOut.remarks = null
  //填充产品编码信息
  formDeviceOut.deviceCode = row.deviceCode
  formDeviceOut.deviceTypeId = row.deviceTypeDto.deviceTypeId
  //打开弹窗
  formDeviceOutDrawerRef.value.open()
}
// 出入库记录
const handleShowRecords = (row) => {
  showRecord_deviceId.value = row.deviceId
  dialogTableVisible_record.value = true
}

// 查看出入库记录弹窗-----------
const dialogTableVisible_record = ref(false)
const showRecord_deviceId = ref(0)
// 查看出入库记录弹窗-----------

//获取选择的公司
function getCheckedCompany(data) {
  // console.log('checked customer: ', JSON.stringify(data))
  if (data != null) {
    form.customerId = data.id
    form.customerName = data.name
    checkedCompany.value = data
  }
}
//获取选择的工单
function getCheckedOrder(data) {
  // console.log('checked order: ', JSON.stringify(data))
  if (data != null) {
    //入库
    form.orderId = data.orderId
    form.projectId = data.projectId
    form.customerId = data.customerId
    //出库
    formDeviceOut.orderId = data.orderId
    formDeviceOut.projectId = data.projectId
    formDeviceOut.customerId = data.customerId

    //公共显示内容
    checkedOrder.value = data
  }
}
//获取选择的申请人
function getCheckedUser(data) {
  // console.log('checked user: ', JSON.stringify(data))
  if (data != null) {
    //入库
    form.userId = data.id
    form.userName = data.realName
    //出库
    formDeviceOut.userId = data.id
    formDeviceOut.userName = data.realName
    //公共显示内容
    checkedUser.value = data
  }
}
//清除已选择的公司
function cleanCustomer() {
  form.customerId = null
  form.customerName = ""
  checkedCompany.value = null
}
//清除已选择的工单
function cleanOrder() {
  form.orderId = null
  form.projectId = null
  form.customerId = null
  checkedOrder.value = null
}
//清除已选择的申请人
function cleanCheckedUser() {
  //入库
  form.userId = null
  form.userName = null
  //出库
  formDeviceOut.userId = null
  formDeviceOut.userName = null
  //公共显示内容
  checkedUser.value = null
}
//产品类型选择框改变事件
function deviceTypeChange(data) {
  //console.log('选择产品类型', JSON.stringify(data))
  form.deviceTypeId = data.deviceTypeId
  form.deviceTypeName = data.deviceTypeName
}

//操作类型改变事件
function opTypeChange() {
  cleanCustomer()
  cleanOrder()
  cleanCheckedUser()
}
</script>